package ar.com.gonzawork.flhandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class LinkDialogActivity extends Activity {
	
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.linkdialog);
		
		Intent gint;
		gint = getIntent();
		
		if(gint.hasCategory(Intent.CATEGORY_BROWSABLE)) {
			
			URL url = null;
			
			try {
				url = new URL(gint.getDataString());
			} catch (MalformedURLException e1) {
				debugeame("new URL", e1);
				e1.printStackTrace();
			}
			
			
			BufferedReader reader = null;
			StringBuilder builder = new StringBuilder();
			
			try {
				
				reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
				
				for (String line; (line = reader.readLine()) != null;) {
					builder.append(line.trim());
				}
				
				int iofenlace = builder.indexOf("Enlace:&nbsp;</div>");
				int ioflink = builder.indexOf("<a href=\"", iofenlace);
				int selstart = ioflink + 9;
				int selend   = builder.indexOf("\"", selstart);
				String htlink = builder.substring(selstart, selend);
				
				Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse(htlink));
				startActivity(browserIntent);
				
			} catch (UnsupportedEncodingException e) {
				debugeame("UnsupportedEncodingException", e);
				e.printStackTrace();
			} catch (IOException e) {
				debugeame("IOException", e);
				e.printStackTrace();
			} finally {
				if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
		    }
			
		}
			
    }
	
	public void debugeame(String tit, Exception e) {
		AlertDialog ale = new AlertDialog.Builder(this).create();
		ale.setTitle(tit);
		ale.setMessage(e.toString());
		ale.setButton("Volver", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		ale.show();
	}
	
}